use crate::components::EditorCoreSelection;
use crate::utils::{
    dom::{create_span, get_selection},
    helper::get_document,
};
use gloo::console::log;

#[derive(Clone, PartialEq)]
pub enum StyleItem {
    Title1,
    Title2,
    Title3,
    Normal,
}

impl StyleItem {
    pub fn build_style(&self) -> String {
        match self {
            Self::Title1 => "font-size:24px;font-weight:bold".to_string(),
            Self::Title2 => "font-size:20px;font-weight:bold".to_string(),
            Self::Title3 => "font-size:18px;font-weight:bold".to_string(),
            Self::Normal => "font-size:14px;font-weight:normal".to_string(),
        }
    }
}

fn apply_title(target_selection: &EditorCoreSelection, style_item: &StyleItem) {
    log!("apply_title");
    if !target_selection.is_focus_on_text() {
        return;
    }
    let selection = get_selection().expect("apply_title/get selection error");
    if selection.range_count() > 0 {
        let _ = selection.remove_all_ranges();
    }
    let document = get_document();
    let range = document
        .create_range()
        .expect("apply_title/create_range error");

    let style_span = create_span(&document);
    style_span.style().set_css_text(&style_item.build_style());
    let _ = range.select_node(&target_selection.focus_node.clone().unwrap());
    let _ = range.surround_contents(&style_span);
}

#[derive(Clone, PartialEq)]
pub enum ElementStyle<'a> {
    Title(&'a StyleItem),
}

impl<'a> ElementStyle<'a> {
    pub fn apply(&self, editor_selection: &'a EditorCoreSelection) {
        match self {
            Self::Title(style_item) => apply_title(editor_selection, style_item),
        }
    }
}
